package org.hgvc.webapp.ets.jsf.beans.mastersetup;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.component.UIParameter;
import javax.faces.event.ActionEvent;

import org.hgvc.webapp.ets.bo.Product;
import org.hgvc.webapp.ets.constant.CommonConstant;
import org.hgvc.webapp.ets.spring.service.MasterSetupService;
import org.jocsb.base.AbstractBean;
import org.jocsb.base.exception.BaseException;


public class ProductBean extends AbstractBean {
	public static final String BEAN_NAME="agentBean";
	private MasterSetupService service;
	private List<Product> productList;
	private Product product;
	public static final String NAV_LIST_PRODUCT="listProduct";
	public static final String NAV_ADD_PRODUCT="addProduct";
	public static final String NAV_EDIT_PRODUCT="editProduct";
	 
	public MasterSetupService getService() {
		return service;
	}
	public void setService(MasterSetupService service) {
		this.service = service;
	}
	public Product getProduct() {
		return product;
	}
	public void setProduct(Product product) {
		this.product = product;
	}
	public List<Product> getProductList() {
		try{
			productList = service.getProductList();
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		return productList;
	}
	public void setProductList(List<Product> productList) {
		this.productList = productList;
	}
	
	public String navCreationAction(){
		product = new Product();
		return NAV_ADD_PRODUCT;
	}
	
	public String createAction(){
		try{
			product.setCreatedBy(getThisUser());
			product.setCreatedDate(new Date());
			product.setIsDeleted(CommonConstant.NOT_DELETED);
			service.saveProduct(product);
			return NAV_LIST_PRODUCT;
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		return NAV_ADD_PRODUCT;
	}
	
	public void editListener(ActionEvent actionEvent){
		product = null;
		UIParameter parameter = (UIParameter)actionEvent.getComponent().findComponent("productId");
		String productId = (String)parameter.getValue();
		for(Product a:productList){
			if(a.getProductId().equalsIgnoreCase(productId)){
				product = a;
				break;
			}
		}
	}
	
	public String navEditAction(){
		return NAV_EDIT_PRODUCT;
	}
	
	public String editAction(){
		try{
			product.setModifiedBy(getThisUser());
			product.setModifiedDate(new Date());
			service.updateProduct(product);
			return NAV_LIST_PRODUCT;
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		
		return NAV_EDIT_PRODUCT;
	}
	
	public String deleteAction(){
		try{
			
			List<Product> deleteList = new ArrayList<Product>();
			for(Product a:productList){
				if(a.isMarkAsAction()){
					deleteList.add(a);
				}
			}
			service.deleteProducts(deleteList);
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		return NAV_LIST_PRODUCT;
	}
}
